<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>设备运行状态</title>
</head>
<link href="../../css/index.css" rel="stylesheet">
<style>
  .scheme-btn {
    position: absolute;
  }
</style>

<body>
  <div id="status-content">
    <div class="message" :class="message.type" v-if="message.text">{{message.text}}</div>
    <div class="edit-content">
      <div>
        <button class="primary-btn" @click="handleReload">
          <img src="../../assets/jiazai.png" v-if="loading.reload" class="loading" />
          刷新时段
        </button>
        <button class="primary-btn" @click="handleChangeStatus(AREA_STATUS.OPEN)">
          <img src="../../assets/jiazai.png" v-if="loading.open" class="loading" />
          开启全部子区
        </button>
        <button class="primary-btn" @click="handleChangeStatus(AREA_STATUS.CLOSE)">
          <img src="../../assets/jiazai.png" v-if="loading.close" class="loading" />
          关闭全部子区
        </button>
        <button class="primary-btn" @click="handleOpenAlg">
          <img src="../../assets/jiazai.png" v-if="loading.close" class="loading" />
          开启算法
        </button>
      </div>
    </div>
    <table border="1" :class="currentSchemeKey ? 'has-scheme' : ''">
      <tr>
        <th colspan="5" class="area-title">子区</th>
        <th colspan="8" class="cross-title">路口</th>
        <th colspan="2" class="area-title">子区操作</th>
      </tr>
      <tr>
        <th class="area-title">子区</th>
        <th class="area-title">运行时段</th>
        <th class="area-title">运行</th>
        <th class="area-title">开始</th>
        <th class="area-title">未对齐</th>
        <th class="cross-title">路口</th>
        <th class="cross-title">协调</th>
        <th class="cross-title">续锁</th>
        <th class="cross-title">未协调</th>
        <th v-for="item in schemeConfig" :key="item.key" class="cross-title">
          {{item.label}}
        </th>
        <th class="area-title">操作</th>
        <th class="area-title">绿波</th>
      </tr>
      <tr class="center" 
        v-for="(item, index) in renderData" :key="item.subId"
        :class="index % 2 === 0 ? 'odd' : 'even'">
        <!-- 子区名称 -->
        <td :rowspan="item.rowNum" v-if="item.isFirst"> {{item.subId}} </td>
        <!-- 运行时间 -->
        <td :rowspan="item.rowNum" v-if="item.isFirst">
          <div v-for="(ele, eleIndex) in item.timeConfigs" v-if="item.timeConfigs && item.timeConfigs.length">
            <div>
              {{ele.start}}
            </div>
            <div>↓</div>
            <div>
              {{ele.end}}
            </div>
            <br v-if="eleIndex < item.timeConfigs.length - 1" />
          </div>
          <div v-else>-</div>
        </td>
        <!-- 运行状态 -->
        <td :rowspan="item.rowNum" v-if="item.isFirst" :class="`${item.running ? 'status-true' : 'status-false'}`"></td>
        <!-- 开始状态 -->
        <td :rowspan="item.rowNum" v-if="item.isFirst" :class="`${item.start ? 'status-true' : 'status-false'}`"></td>
        <!-- 未 对 齐 -->
        <td :rowspan="item.rowNum" v-if="item.isFirst" :class="`${item.disAlign.status ? 'text-true' : 'text-false'}`">
          <span>{{item.disAlign.cnt}}/{{item.disAlign.max}}</span>
        </td>
        <!-- 路口 -->
        <td>
          {{item.siteId}}
          <button class="scheme-btn" @click="handleClickScheme(item)">
            <img src="../../assets/chakan.png" alt="查看方案" />
          </button>
        </td>
        <!-- 协调状态 -->
        <td :class="`${item.coordStatus ? 'status-true' : 'status-false'}`"></td>
        <!-- 续锁状态 -->
        <td :class="`${item.lockStatus.status ? 'text-true' : 'text-false'}`">
          <span>{{item.lockStatus.cnt}}/{{item.lockStatus.max}}</span>
        </td>
        <!-- 未协调状态 -->
        <td :class="`${item.disCoord.status ? 'text-true' : 'text-false'}`">
          <span>{{item.disCoord.cnt}}/{{item.disCoord.max}}</span>
        </td>
        <!-- 最新方案、协调方案、绿信比方案、运行方案 -->
        <td v-for="schemeItem in schemeConfig" :key="schemeItem.key">
          <div class="scheme-show" v-if="item[schemeItem.key].schemeInfo">
            <div class="scheme-msg">
              <div class="scheme-msg-item">C: {{item[schemeItem.key].schemeInfo.cycle}}</div>
              <div class="scheme-msg-item">O: {{item[schemeItem.key].schemeInfo.offset}}</div>
            </div>
          </div>
          <div v-else>
            -
          </div>
        </td>
        <!-- 操作栏 -->
        <td :rowspan="item.rowNum" v-if="item.isFirst">
          <div>
            <button @click="handleStart(item)">
              <img src="../../assets/jiazai.png" v-if="item.startLoading" class="loading" />
              开启
            </button>
          </div>
          <br />
          <div>
            <button @click="handleStop(item)">
              <img src="../../assets/jiazai.png" v-if="item.endLoading" class="loading" />
              停止
            </button>
          </div>
        </td>
        <!-- 查看绿性比 -->
        <td :rowspan="item.rowNum" v-if="item.isFirst">
          <template v-for="(type, typeIndex) in schemeConfig" :key="type.key">
            <div v-if="!type.label.includes('运行')">
              <button @click="handleGreen(item, type.key)">
                <img src="../../assets/jiazai.png" v-if="item.startLoading" class="loading" />
                {{type.label?.split('[')[0]}}
              </button>
            </div>
            <br v-if="!type.label.includes('运行') && !type.label.includes('绿信比')" />
          </template>
        </td>
      </tr>
      <tr v-if="loading.table">
        <th colspan="15">
          <img src="../../assets/jiazai.png" class="loading" />
        </th>
      </tr>
    </table>
    <!-- 方案弹窗 -->
    <div class="drawer" :class="currentSchemeKey ? '' : 'hidden-scheme'">
      <div class="drawer-title" v-if="currentSchemeKey">
        <div>
          子区【{{currentScheme.subId}}】 - 路口【{{currentScheme.siteId}}】
        </div>
        <div @click="handleClose">
          <img src="../../assets/guanbi.png" />
        </div>
      </div>
      <div class="drawer-content" v-if="currentSchemeKey">
        <div class="drawer-content-item" v-for="schemeType in schemeConfig" :key="schemeType.key">
          <div class="first-title">{{schemeType.label}}</div>
          <div class="common-title">方案信息</div>
          <div class="msg-item">
            <div class="msg-item-label">时间:</div>
            <div class="msg-item-value">{{currentScheme[schemeType.key]?.genTime}}</div>
          </div>
          <div class="msg-item">
            <div class="msg-item-label">周期:</div>
            <div class="msg-item-value">{{currentScheme[schemeType.key]?.schemeInfo?.cycle}}s</div>
          </div>
          <div class="msg-item">
            <div class="msg-item-label">相位差:</div>
            <div class="msg-item-value">{{currentScheme[schemeType.key]?.schemeInfo?.offset}}s</div>
          </div>
          <div class="msg-item">
            <div class="msg-item-label">类型:</div>
            <div class="msg-item-value">{{currentScheme[schemeType.key]?.schemeInfo?.type}}</div>
          </div>
          <div class="common-title">阶段信息</div>
          <template v-if="currentScheme[schemeType.key]?.schemeInfo?.stages">
            <div class="stage-item" v-for="item in currentScheme[schemeType.key].schemeInfo.stages" :key="item.stageNo">
              <div class="msg-item">
                <div class="msg-item-label">编号:</div>
                <div class="msg-item-value">{{item.stageNo}}</div>
              </div>
              <div class="msg-item">
                <div class="msg-item-label">时长:</div>
                <div class="msg-item-value">{{item.execTime}}s</div>
              </div>
            </div>
          </template>
          <div v-else class="no-data">暂无数据</div>
        </div>
      </div>
    </div>
  </div>
</body>
<script src="../../js/mock/firstEdition/statusMock.js"></script>
<script src="../../config.js"></script>
<script src="../../js/vue3.js"></script>
<script>
  const { createApp, ref, nextTick, reactive, onMounted, onUnmounted, watch, computed } = Vue
  const app = createApp({
    setup() {
      // 渲染数据
      let renderData = ref([])

      const schemeConfig = {
        recvScheme: { key: 'recvScheme', label: '最新[收到]' },
        coordScheme: { key: 'coordScheme', label: '协调[带标]' },
        splitScheme: { key: 'splitScheme', label: '绿信比[不带标]' },
        runScheme: { key: 'runScheme', label: '运行[上传]' },
      }

      const MESSAGE_TYPE = {
        'SUCCESS': 'success',
        'INFO': 'info',
        'ALERT': 'alert',
        'ERROR': 'error'
      }

      const loading = reactive({
        reload: false, // 刷新时段
        open: false, // 开启子区开关
        close: false, // 关闭子区开关
        table: false, // 表格刷新
        editTime: false, // 编辑时段
        deleteTime: false, // 删除时段
      })

      const message = reactive({
        type: '',
        text: ''
      })

      // 弹窗消息1.5秒消失
      watch(
        () => message.text,
        () => {
          if (message.text) {
            setTimeout(() => {
              message.text = ''
            }, 2000)
          }
        }
      )

      const AREA_STATUS = {
        OPEN: 1,
        CLOSE: 0
      }

      // 当前查看的方案信息
      const currentScheme = computed(() => {
        const result = renderData.value.find(item => item.siteId === currentSchemeKey.value)
        return result
      })

      // 当前查看的方案类型
      const currentSchemeKey = ref('')

      // 查看方案 data 查看的数据 key 查看的方案类型
      const handleClickScheme = (data) => {
        currentSchemeKey.value = data.siteId
      }

      // 关闭方案查看
      const handleClose = () => {
        currentSchemeKey.value = ''
      }

      // 初始化渲染数据
      const transformData = (originData) => {
        let data = []
        originData?.forEach((element, eleIndex) => {
          element.siteStatuses.forEach((item, itemIndex) => {
            data.push({
              ...element,
              ...item,
              isFirst: itemIndex === 0, // 是否子区的第一条数据，第一条数据展示子区
              rowNum: element.siteStatuses?.length || 1 // 子区的合并行数
            })
          })
        });
        return data
      }

      // 获取接口返回的数据
      const getInitData = (isFirst = false) => {
        isFirst && (loading.table = true)
        fetch(apiUrl + '/utch-itsg/coord/statusAll')
          .then(res => res.json())
          .then(res => {
            renderData.value = transformData(res.data)
          })
          .catch(error => {
            message.text = '列表返回数据失败'
            message.type = MESSAGE_TYPE.ERROR
          }).finally(() => {
            loading.table = false
            if (isMock && isFirst) {
              message.text = '请注意当前处于mock模式'
              message.type = MESSAGE_TYPE.INFO
              renderData.value = transformData(mockData.data)
            }
          })
      }

      // 开启
      const handleStart = (item) => {
        const result = confirm('您确定要开启吗?')
        if (result === false) return
        item.startLoading = true
        fetch(apiUrl + '/utch-itsg/coord/start?ssId=' + item.subId)
          .then(() => {
            message.text = `子区${item.subId}开启成功`
            message.type = MESSAGE_TYPE.SUCCESS
          })
          .catch(error => {
            message.text = error.msg || `子区${item.subId}开启失败`
            message.type = MESSAGE_TYPE.ERROR
          }).finally(() => {
            item.startLoading = false
          })
      }

      // 停止
      const handleStop = (item) => {
        const result = confirm('您确定要停止吗?')
        if (result === false) return
        item.endLoading = true
        fetch(apiUrl + '/utch-itsg/coord/stop?ssId=' + item.subId)
          .then(() => {
            message.text = `子区${item.subId}停止成功`
            message.type = MESSAGE_TYPE.SUCCESS
          })
          .catch(error => {
            message.text = error.msg || `子区${item.subId}停止失败`
            message.type = MESSAGE_TYPE.ERROR
          }).finally(() => {
            item.endLoading = false
          })
      }

      // 刷新全部时段
      const handleReload = () => {
        loading.reload = true
        fetch(apiUrl + '/utch-itsg/coord/updateAll')
          .then(() => {
            message.text = `时段刷新成功`
            message.type = MESSAGE_TYPE.SUCCESS
          })
          .catch(error => {
            message.text = error.msg || `时段刷新失败`
            message.type = MESSAGE_TYPE.ERROR
          }).finally(() => {
            loading.reload = false
          })
      }

      // 开启关闭
      const handleChangeStatus = (state) => {
        const result = confirm(`您确定要${state === AREA_STATUS.OPEN ? '开启' : '关闭'}全部吗?`)
        if (result === false) return
        state === AREA_STATUS.OPEN ? loading.open = true : loading.close = true
        fetch(apiUrl + '/utch-itsg/coord/updateCoordStatus?status=' + state)
          .then(() => {
            message.text = `状态更新成功`
            message.type = MESSAGE_TYPE.SUCCESS
          })
          .catch(error => {
            message.text = error.msg || `状态更新失败`
            message.type = MESSAGE_TYPE.ERROR
          }).finally(() => {
            loading.open = false
            loading.close = false
          })
      }

      // 开启算法
      const handleOpenAlg = () => {
        const result = confirm(`接口开发中，敬请期待`)
      }

      // 进入到绿波界面生成绿波方案
      const handleGreen = (item, type) => {
        let schemes = []
        item.siteStatuses.forEach(item => {
          item[type].schemeInfo && schemes.push(item[type].schemeInfo)
        })
        if (schemes.length !== item.siteStatuses.length) {
          message.text = '当前子区绿波方案不全'
          message.type = MESSAGE_TYPE.ERROR
          return
        }
        window.localStorage.setItem('greenSchemes', JSON.stringify({type, schemes, subId: item.subId, randomId: Math.random()}))
      }

      let timer = null
      onMounted(() => {
        getInitData(true)
        if (!isMock) {
          timer = setInterval(() => {
            getInitData()
          }, pollingTime * 1000)
        }
      })

      onUnmounted(() => {
        timer && clearInterval(timer)
      })
      return {
        AREA_STATUS,
        renderData,
        schemeConfig,
        currentSchemeKey,
        currentScheme,
        message,
        loading,
        handleClickScheme,
        handleClose,
        handleStart,
        handleStop,
        handleReload,
        handleChangeStatus,
        handleGreen,
        handleOpenAlg
      }
    }
  })
  app.mount("#status-content");
</script>

</html>